//
//  ShakeOpenController.m
//  PropertyMananger
//
//  Created by Mansion on 17/3/5.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "ShakeOpenController.h"
#import "ShakeOpenView.h"
#import "DrawClickView.h"
#import "MyKeyCaseController.h"
#import "MDkeyModel.h"

@interface ShakeOpenController ()<UINavigationControllerDelegate>
@property (nonatomic,strong) ShakeOpenView * shakeOpenView;
@property (nonatomic,strong) DrawClickView * drawView;

@property (nonatomic,strong) NSMutableArray * keyArray;

// ---- 开门处理
@property (nonatomic , assign) BOOL Bluetooth;//用于判断蓝牙是否已经打开
@property (nonatomic , strong) NSMutableArray * shakeImages;
@property (nonatomic , assign) BOOL timeOpen;

//智能门禁数据
@property (nonatomic , strong) UIImageView * equipmentView;
@property (nonatomic , strong) UILabel * shakeLable;
@property (nonatomic , strong) NSMutableArray * keyIdArray;
@property (nonatomic , strong) NSMutableArray * keyNameArray;
@property (nonatomic , strong) NSString * keyUserId;

@end

@implementation ShakeOpenController
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    // 断网状态或未登录状态下调用本地，有网络则调用请求网络
    if (userModel.WorkerID == nil || userModel.CommunityID == nil) {
        [self getLocalKey];
    }else{
        [self appleKeyFoRNet];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
     self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self initTitleViewName:@"摇一摇开门"];
     self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    
    [self openDoor];
    [self createShakeAnimatonUI];
    
    [self appleKeyFoRNet];
    
}
#pragma mark ------------------- 开门数据相关
- (void)openDoor{
    
    //智能门禁
    self.keyIdArray= [[NSMutableArray alloc] init];
    self.keyNameArray = [[NSMutableArray alloc] init];
    self.keyArray = [[NSMutableArray alloc]init];
    self.keyUserId =@"AppID";
    
}

- (void)createShakeAnimatonUI{

    self.shakeOpenView = [[ShakeOpenView alloc]initWithFrame:CGRectMake(0, 0, BHscreenW, BHscreenH)];
    
    [self.view addSubview:self.shakeOpenView];
    
    [self.shakeOpenView.backBtn addTarget:self action:@selector(returnBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.shakeOpenView.myKeyButton addTarget:self action:@selector(myKeyButton) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer * entranceGuardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(IntelligentOpenGuardTap)];
    entranceGuardTap.numberOfTapsRequired = 1;
    entranceGuardTap.numberOfTouchesRequired = 1;
    self.shakeOpenView.imageView.userInteractionEnabled = YES;
    [self.shakeOpenView.imageView addGestureRecognizer:entranceGuardTap];
    
    // 设置动画图片数组
    self.shakeImages = [[NSMutableArray alloc] init];
    for(int j = 0 ; j < 10 ; j ++){
        int num = j%2;
        UIImage * image = [UIImage imageNamed:[NSString stringWithFormat:@"ico_yaoyiyao_%d",num+2]] ;
        [self.shakeImages addObject:image];
    }

    
}
- (void)click:(UITapGestureRecognizer *)tap{

    self.drawView = [[DrawClickView alloc]init];;
    [self.view addSubview:self.drawView];
    
    [self.drawView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).with.offset(0);
        make.top.equalTo(self.view).with.offset(50);
        make.size.mas_equalTo(CGSizeMake(270, 190));
    }];

    
    //抽奖点击事件
    [self.drawView.drawButton addTarget:self action:@selector(drawClick:) forControlEvents:UIControlEventTouchUpInside];

}
- (void)drawClick:(UIButton *)button{
    
    DLog(@"点击确认");
}
- (void)returnBtn:(UIButton *)button{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)myKeyButton{

    MyKeyCaseController * myKeyVC = [[MyKeyCaseController alloc]init];
    
    [self.navigationController pushViewController:myKeyVC animated:YES];
    

}
#pragma mark - 钥匙获取
//从网络获取钥匙
-(void)appleKeyFoRNet{

    NSDictionary * param = @{
                             @"cid":userModel.CommunityID,
                             @"Phone":userModel.Tel,
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"getkeylist\",\"version\":\"V1.0\"}",
                             };
    DLog(@"提交的参数 == %@",param);
    [HomeNetWorkRequest postMDKeySuccess:^(id data) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [self.keyIdArray removeAllObjects];
        [self.keyNameArray removeAllObjects];
        
            NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
            NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
            
            DLog(@"钥匙 === %@",array);
        
        for (NSDictionary * dict in array) {
            
            MDkeyModel * model = [[MDkeyModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            
            [self.keyArray addObject:model];
            
           
            [self.keyNameArray addObject:model.DeviceName];
         
            if([self compareNowDateWithAnotherDay:model.ExpireTime]){
             [self.keyIdArray addObject:model.KeyCode];
             _timeOpen = YES;
            }else{
                [self.keyIdArray addObject:@""];
                 _timeOpen = NO;
            }
            
        }
     
            //缓存数据到本地
            NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
            NSString * key = [NSString stringWithFormat:@"MDKey%@",userModel.CommunityName];
            [setting setObject:data2 forKey:key];
            
        
    } Fail:^(NSString *errorDes) {
        NSLog(@"%@",errorDes);
        // 网络超时调用本地（测试）
        [self getLocalKey];
    } param:param];
}

//从本地获取钥匙
-(void)getLocalKey{
    
    NSUserDefaults * settings = [NSUserDefaults standardUserDefaults];
    NSData *data = [settings objectForKey:@"MDKey"];
    if(data != nil)//本地用户数据存在
    {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"keylist"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        
        if(array.count != 0)//本地钥匙数据存在
        {
            if (self.keyIdArray != 0 || self.keyNameArray != 0) {
                [self.keyIdArray removeAllObjects];
                [self.keyNameArray removeAllObjects];
            }
            
            for (NSDictionary * dict in array) {
                
                MDkeyModel * model = [[MDkeyModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                
                [self.keyArray addObject:model];
                
                
                [self.keyNameArray addObject:model.DeviceName];
                
                if([self compareNowDateWithAnotherDay:model.ExpireTime]){
                    [self.keyIdArray addObject:model.KeyCode];
                    _timeOpen = YES;
                }else{
                    [self.keyIdArray addObject:@""];
                    _timeOpen = NO;
                }
                
            }

        }else{//本地钥匙数据不存在
            [self.keyIdArray removeAllObjects];
            [self.keyNameArray removeAllObjects];
        }
    }
    
}
//比较日期大小
-(BOOL)compareNowDateWithAnotherDay:(NSString *)anotherDay
{
    NSDate * date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddhhmm"];
    NSString * today = [dateFormatter stringFromDate:date];
    double todayNum = [today doubleValue];
    
    NSMutableString * muStr = [[NSMutableString alloc] init];
    NSArray * array = [anotherDay componentsSeparatedByString:@" "];
    NSArray * array1 = [array[0] componentsSeparatedByString:@"-"];
    NSArray * array2 = [array[1] componentsSeparatedByString:@":"];
    for(int i = 0 ; i < array1.count ; i ++){
        [muStr appendFormat:@"%@",array1[i]];
    }
    for(int i = 0 ; i < array2.count ; i ++){
        [muStr appendFormat:@"%@",array2[i]];
    }
    double strNum = [muStr doubleValue];
    if(todayNum < strNum ){ //当前时间小与有效时间   可以开门
        
        return YES;
    }else{
        return NO;
    }
    
}
#pragma mark - 开门设置
#pragma mark - 智能门禁点击图片响应事件
- (void)IntelligentOpenGuardTap{
    
    //摇一摇手机震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //点击摇一摇
    MDManager *manager = [MDManager sharedManager];
    [manager setSoundType:OpenSoundTypeCustom];
    [manager setOpenDoorSuccessSound:@"custom1.caf"];
    
    self.shakeOpenView.shakeImg.image = IMG(@"");
    
    //@[@"00000002&#20650101&#MD_BLZX_C929&#80D5D82970A06D5A36615458CE8133E492D6A9A635D74871F08E3A03DE9A2951&#E60A4FEB3F4B812EAB998627E86EC675&#31851222C929&#BLZXC160600875"] @[@"公司大门"]
    [manager shakeOpenDoorWithUserId:self.keyUserId UseKeyIdList:self.keyIdArray KeyNameList:self.keyNameArray CommunityList:self.keyNameArray isSupportShake:YES Success:^(NSDictionary *keyInfo) {
        
        [MBProgressHUD showSuccess:[NSString stringWithFormat:@"%@---开门成功",keyInfo[@"key_name"]] time:2];
        
        //摇一摇图片处理
        self.shakeOpenView.shakeImg.image = [UIImage imageNamed:@"ico_yaoyiyao_1"];
        [self.shakeOpenView.imageView.layer removeAllAnimations];
        
        
    } Failure:^(ErrorType errorCode) {
        NSString * str = [NSString stringWithFormat:@"%ld",(long)errorCode];
        //开门失败
        [self openDoorFailureWithString:str];
        //摇一摇图片处理
        self.shakeOpenView.shakeImg.image = [UIImage imageNamed:@"ico_yaoyiyao_1"];
        [self.shakeOpenView.imageView.layer removeAllAnimations];
        
    }];
    
    //震动动画
    self.shakeOpenView.imageView.animationImages = self.shakeImages;
    self.shakeOpenView.imageView.animationDuration = 2;
    [self.shakeOpenView.imageView startAnimating];
    
}
//摇一摇开门
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (!(motion == UIEventSubtypeMotionShake))return;
    //摇一摇手机震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //摇一摇图片处理
    MDManager *manager = [MDManager sharedManager];
    [manager setSoundType:OpenSoundTypeDefault2];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = @"正在努力开门中...";
//    // 隐藏时从父控件中移除
//    hud.removeFromSuperViewOnHide = YES;
//    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
//    hud.userInteractionEnabled = YES;
    
    self.shakeOpenView.shakeImg.image = IMG(@"");
    
     //@[@"00000002&#20650101&#MD_BLZX_C929&#80D5D82970A06D5A36615458CE8133E492D6A9A635D74871F08E3A03DE9A2951&#E60A4FEB3F4B812EAB998627E86EC675&#31851222C929&#BLZXC160600875"] @[@"公司大门"]
    [manager shakeOpenDoorWithUserId:self.keyUserId UseKeyIdList:self.keyIdArray KeyNameList:self.keyNameArray CommunityList:self.keyNameArray isSupportShake:YES Success:^(NSDictionary *keyInfo) {

//         [MBProgressHUD hideHUDForView:self.view];
        
        [MBProgressHUD showSuccess:[NSString stringWithFormat:@"%@---开门成功",keyInfo[@"key_name"]] time:2];

        //摇一摇图片处理
        self.shakeOpenView.shakeImg.image = [UIImage imageNamed:@"ico_yaoyiyao_1"];
        [self.shakeOpenView.imageView.layer removeAllAnimations];

        
    } Failure:^(ErrorType errorCode) {
        NSString * str = [NSString stringWithFormat:@"%ld",(long)errorCode];
        //开门失败
        [self openDoorFailureWithString:str];
        //摇一摇图片处理
         self.shakeOpenView.shakeImg.image = [UIImage imageNamed:@"ico_yaoyiyao_1"];
        [self.shakeOpenView.imageView.layer removeAllAnimations];

//         [MBProgressHUD hideHUDForView:self.view];

    }];
    
    //震动动画
    self.shakeOpenView.imageView.animationImages = self.shakeImages;
    self.shakeOpenView.imageView.animationDuration = 2;
    [self.shakeOpenView.imageView startAnimating];
    
}

//开门失败
-(void)openDoorFailureWithString:(NSString *)string{
    
    if([string isEqualToString:@"-2002"]){ //蓝牙未打开
        [self openDoorFailureAlertWithMessage:@"蓝牙未打开，是否打开蓝牙？" Cancel:@"否" Confirm:@"是" Type:string];
        
    }else{
        [MBProgressHUD showError:[NSString stringWithFormat:@"开门失败（%@）",string] time:2];
    }
}

//开门失败提示信息
-(void)openDoorFailureAlertWithMessage:(NSString *)message Cancel:(NSString *)cancel Confirm:(NSString *)confirm Type:(NSString *)type{
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:confirm style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([type isEqualToString:@"-2002"]){//蓝牙未打开
            NSURL *url = [NSURL URLWithString:@"prefs:root=Bluetooth"];
            
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                
                [[UIApplication sharedApplication]openURL:url];
            }
        }else if ([type isEqualToString:@"-2013"]||[type isEqualToString:@"-2018"]||[type isEqualToString:@"-2014"]){//钥匙错误 -- 钥匙失效 -- 参数为空
  
        }
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
  
}



@end
